package com.gton.person.service.impl;


import com.gton.person.entity.Role;
import com.gton.person.entity.User;
import com.gton.person.mapper.UserMapper;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * @Author: 郭童
 * Date: 2020/11/3 20:46
 * @Description:
 */
@Service("userService")
public class UserService implements UserDetailsService {


    @Resource
    private UserMapper userMapper;

    public User getUserByName(String userName) {
        return userMapper.getUserByName(userName);
    }

    /**
     * 自定义认证业务
     *
     * @param userName 为浏览器输入的用户名
     * @return UserDetails 为SpringSecurity自己的用户对象
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {
        try {
            //根据用户名查询
            User user = getUserByName(userName);
            if (user == null) {
                throw new Exception("账户不存在");
            }
            //获取role权限，根据用户表id在权限表里面查出该用户的权限信息
            List<Role> roles = userMapper.getRolesByUid(user.getId());
            //Stream操作，比如排序，筛选空，
            user.setRoles(roles);
            roles.forEach(System.out::println);
            System.out.println(user);
            return user;
        } catch (Exception e) {
            //在SpringSecurity中，return null即为认证失败
            return null;
        }
    }

}
